package com.zzc.alfred.entity.service.index;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.ansj.lucene4.AnsjAnalysis;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.zzc.alfred.entity.model.ProductIndexModel;
import com.zzc.alfred.entity.util.LuceneUtils;

/**
 * 数据库查询
 * 
 * @author famous
 *
 */
public class ProductIndexModelIndexService {

	private static Directory d;
	private static IndexWriterConfig conf;
	private static final Properties PROPERTIES = new Properties();
	static Analyzer analyzer = new AnsjAnalysis();

	static {
		try {
			InputStream is = DataSourceFactory.class.getResourceAsStream("/common.properties");
			PROPERTIES.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			/** Lucene 5 专用 */
			// d =
			// FSDirectory.open(Paths.get(PROPERTIES.getProperty("index_path")));
			d = FSDirectory.open(new File(PROPERTIES.getProperty("index_path")));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		// conf = new IndexWriterConfig(analyzer);
		conf = new IndexWriterConfig(Version.LATEST, analyzer);
		conf.setOpenMode(OpenMode.CREATE_OR_APPEND);

	}

	/**
	 * 查询指定的ID在索引中是否存在
	 * 
	 * @param id
	 * @return
	 */
	public boolean getProduct(String id) {
		TermQuery query = new TermQuery(new Term("id", id));
		try {
			TopDocs hits = LuceneUtils.getIndexSearcher(LuceneUtils.getIndexReader(d, true)).search(query, 1);
			if (hits.totalHits > 0) {
				return true;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 新增商品
	 * 
	 * @param id
	 * @return
	 */
	public void addProduct(List<ProductIndexModel> indexModels) {
		IndexWriter indexWriter = LuceneUtils.getIndexWriter(d, conf);
		// IndexWriter indexWriter = LuceneUtil.getIndexWriter();
		List<Document> documents = new ArrayList<Document>();
		for (ProductIndexModel model : indexModels) {
			Document document = getDoucument(model);
			documents.add(document);
		}
		try {
			indexWriter.addDocuments(documents);
			indexWriter.forceMerge(1);
			indexWriter.commit();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新商品
	 * 
	 * @param indexModels
	 */
	public void updateProduct(List<ProductIndexModel> indexModels) {
		// IndexWriter indexWriter = LuceneUtil.getIndexWriter();
		IndexWriter indexWriter = LuceneUtils.getIndexWriter(d, conf);
		List<Document> documents = new ArrayList<Document>();
		for (ProductIndexModel model : indexModels) {
			Document document = getDoucument(model);
			documents.add(document);
		}
		try {
			for (Document document : documents) {
				indexWriter.updateDocument(new Term("id", document.get("id")), document);
			}
			indexWriter.commit();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取总数
	 * 
	 * @param indexFile
	 * @return
	 */
	public int findIndexDbCount(String indexFile) {
		int total = 0;
		try {
			IndexReader reader = LuceneUtils.getIndexReader(d, true);
			// LuceneUtil.getIndexReader();// 读取数据
			total = reader.numDocs();// 数据总量
			reader.close();// 释放资源
		} catch (Exception e) {
			e.printStackTrace();
		}
		return total;
	}

	/**
	 * 实体和document转换
	 * 
	 * @param model
	 * @return
	 */
	private Document getDoucument(ProductIndexModel model) {
		Document document = new Document();
		document.add(new StringField("id", model.getId(), Store.YES));
		document.add(new StringField("skuId", model.getSkuId(), Store.YES));
		document.add(new TextField("brandName", model.getBrandName() == null ? "" : model.getBrandName(), Store.YES));
		document.add(new TextField("productName", model.getProductName(), Store.YES));
		document.add(new TextField("params", model.getParams(), Store.YES));
		document.add(new StringField("imageUrl", model.getImageUrl(), Store.YES));
		document.add(new StringField("productUrl", model.getProductUrl(), Store.YES));
		document.add(new DoubleField("price", model.getPrice() == null ? 0.0 : model.getPrice(), Store.YES));
		document.add(new StringField("webSource", model.getWebSource(), Store.YES));
		return document;
	}

	public static void main(String[] args) {

	}

}
